<template>
  <van-nav-bar
    title="登录/注册"
    left-text="返回"
    left-arrow
    @click-left="onClickLeft"
  />
  <van-form ref="formBox" @submit="submit">
    <van-cell-group inset>
      <van-field
        v-model="ruleForm.phone"
        name="phone"
        label="手机号"
        label-width="50rpx"
        center
        :rules="[
          { required: true, message: '手机号为必填项的哦~' },
          { pattern: /^1[34578][0-9]{9}$/, message: '手机号格式不对哦~' },
        ]"
      >
        <template #button>
          <van-button
            class="form-btn"
            size="small"
            type="primary"
            :disabled="button.disable"
            @click="sendCode"
          >
            {{ button.text }}
          </van-button>
        </template>
      </van-field>
      <van-field
        v-model="ruleForm.code"
        label="验证码"
        label-width="50rpx"
        center
        :rules="[
          { required: true, message: '验证码为必填的哦~' },
          { pattern: /^\d{6}$/, message: '验证码必须是六位数字~' },
        ]"
      />
    </van-cell-group>
    <div style="margin: 20px 40px">
      <van-button round block type="primary" native-type="submit">
        立即登录/注册
      </van-button>
    </div>
  </van-form>
</template>

<script>
import { reactive, toRefs, ref } from "@vue/reactivity";
import api from "@/api/index";
import { Toast } from "vant";
import { onBeforeUnmount } from "@vue/runtime-core";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
export default {
  name: "Login",
  setup() {
    let store = useStore(); //仓库
    let router = useRouter(); //路由
    let route = useRoute(); //路由

    let state = reactive({
      ruleForm: {
        phone: "",
        code: "",
      },
      button: {
        text: "发送验证码",
        disable: false, //表示可以点击
      },
    });

    let formBox = ref(null);
    // 发送验证码
    let timer = null; //定时器
    let sendCode = async () => {
      // 先验证表单内容
      // formBox.value.validate('phone').then(res=>{
      //   console.log("校验通过");
      // }).catch(err=>{
      //   console.log('校验不通过');
      // })

      try {
        await formBox.value.validate("phone");
        // await下面的代码相当于then中的代码
        // console.log("验证通过");

        // 调用后端接口获取验证码
        let res = await api.phoneCode(state.ruleForm.phone);
        console.log(res);
        if (res.code !== 0) {
          Toast.fail("验证码发送失败");
          return;
        }
        // 成功获取验证码
        state.button.disable = true;
        state.button.text = "30秒";
        let num = 30;
        timer = setInterval(() => {
          num--;
          if (num <= 0) {
            clearInterval(timer);
            state.button.text = "重新发送";
            state.button.disable = false;
            return;
          }
          state.button.text = `${num < 10 ? "0" + num : num}秒`;
        }, 1000);
      } catch (err) {
        // console.log("验证不通过");
      }
    };
    // 清除定时器
    onBeforeUnmount(() => clearInterval(timer));

    // 表单 提交
    let submit = async () => {
      let { code, token } = await api.login(state.ruleForm);
      if (code !== 0) {
        Toast.fail("登录失败了~");
        return;
      }
      Toast.success("登录成功");

      // 登录成功后,做什么?
      //1) 把token存储在localstorage中
      localStorage.setItem("tk", token);
      // 2) 修改仓库中islogin状态
      store.commit("changeIsLogin", true);
      // 3) 获取用户信息
      store.dispatch("changeInfoAsync");
      //4) 登录成功后,暂且跳转到个人中心
      router.replace("/person")
      // let { to } = route.query;
      // to ? router.replace(to) : router.go(-1);
    };
    let onClickLeft = () => history.back();
    return {
      ...toRefs(state),
      sendCode,
      formBox,
      submit,
      onClickLeft,
    };
  },
};
</script>

<style lang="less" scoped>
.van-form {
  margin-top: 50px;

  .form-btn {
    width: 78px;
  }
}
/deep/ .van-icon,
/deep/ .van-nav-bar__text {
  color: #000;
}
</style>